package com.fushenlan.epidemicControl.config;

import com.fushenlan.epidemicControl.sms.EncryptUtil;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import java.util.Properties;

/**
 * @author Administrator
 * @date 2022/4/23 13:51
 */
@Component
@Configuration
@Data
@Profile({"dev"})
public class SSHConnectConfig {

    // 自定义的中转接口，需要和数据源接口设置一样，本地端口
    @Value("${sshconfig.mysql.local-port}")
    private Integer mysqlLocalPort;

    // 服务器端SSH端口 默认是22
    @Value("${sshconfig.ssh.remote-port}")
    private Integer sshRemotePort;

    // SSH用户名
    @Value("${sshconfig.ssh.username}")
    private String sshUserName;

    // SSH密码
    @Value("${sshconfig.ssh.password}")
    private String sshPassword;

    // 连接到哪个服务端的SSH
    @Value("${sshconfig.ssh.remote-server}")
    private String sshRemoteServer;

    // 服务端的mysql服务（内网）
    @Value("${sshconfig.mysql.remote-server}")
    private String mysqlRemoteServer;
    // 服务端的数据库端口（内网）
    @Value("${sshconfig.mysql.remote-port}")
    private Integer mysqlRemotePort;

    //represents each ssh session
    private Session session;

    @Autowired
    private EncryptUtil encryptUtil;

    /**
     * 创建SSH连接
     */
    public void createSSH() throws Throwable {

        JSch jsch = new JSch();
        // 需要用到了开启
        session = jsch.getSession(sshUserName, sshRemoteServer, sshRemotePort);
        session.setPassword(encryptUtil.decrypt(sshPassword));

        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        // 去连接
        session.connect();
        //  设置转发
        session.setPortForwardingL(mysqlLocalPort, mysqlRemoteServer, mysqlRemotePort);
    }

    /**
     * 关闭SSH连接
     */
    public void closeSSH() {
        session.disconnect();
    }
}
